package cn.wolfcode.car.business.web.controller;

import cn.wolfcode.car.base.domain.User;
import cn.wolfcode.car.base.service.IUserService;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.web.AjaxResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("business/statementItem")
public class StatementItemController {
    @Autowired
    private IStatementService statementService;//服务结算
    @Autowired
    private IStatementItemService statementItemService;//明细
    @Autowired
    private IUserService userService;//用户

    //模板前缀
    private static final String prefix = "business/statementItem/";

    //结算单明细页面
    @RequiresPermissions("business:statementItem:itemDetail")
    @RequestMapping("/itemDetail")
    public String itemDetail(Model model, Long statementId) {
        Statement statement = statementService.get(statementId);
        model.addAttribute("statement", statement);
        if (Statement.STATUS_CONSUME.equals(statement.getStatus())) {//如果没支付
            return prefix + "itemAdd";//跳转到明细录入页面
        } else {
            Long payeeId = statement.getPayeeId();
            User payee = userService.get(payeeId);//查当前登陆的用户
            statement.setPayee(payee);//设置到收款人
            return prefix + "itemDetail";//跳转到明细的详情页面
        }
    }

    @RequestMapping("/query")
    @ResponseBody
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        return statementItemService.query(qo);
    }

    //保存项目
    @RequestMapping("/saveItems")
    @ResponseBody
    public AjaxResult saveItems(@RequestBody List<StatementItem> items) {
        //@RequestBody注解: 通过Ajax请求发送JSON数据,可以吧JSON数据封装对象中
        statementItemService.saveItems(items);
        return AjaxResult.success();
    }

    //支付声明
    @RequestMapping("/payStatement")
    @ResponseBody
    public AjaxResult payStatement(Long statementId) {
        statementService.updateStatus(statementId);
        return AjaxResult.success();
    }
}
